package com.codejoys.monitor.startup;

import com.codejoys.monitor.jna.CANLib;
import com.sun.jna.Native;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class CanLibInitializer implements ApplicationRunner, DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(CanLibInitializer.class);

    static CANLib canLib;
    static {
        canLib = Native.load("CanLib", CANLib.class);
    }

    private int canDevicesNum = 0;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("程序启动！");

        canDevicesNum = canLib.InitCanDev();

        logger.info("初始化CAN设备。数目：{}", canDevicesNum);

        for (int i = 0; i < canDevicesNum; i++) {
            final boolean isOpened = canLib.OPenCanDev(i);
            logger.info("打开第{}个CAN设备：{}", i, isOpened);
        }
    }

    @Bean
    public CANLib getCanLib() {
        return canLib;
    }

    @Override
    public void destroy() throws Exception {
        logger.info("程序关闭！");

        for (int i = 0; i < canDevicesNum; i++) {
            final boolean isClosed = canLib.CloseCanDev(i);

            logger.info("关闭第{}个CAN设备：{}", i, isClosed);
        }
    }
}
